package com.freewill.utils;

import com.freewill.common.MainActivity;
import com.freewill.main.R;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {

    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    public void onReceive(Context context, Intent intent) {
        
        if (intent.getAction().equals(ACTION)) {
            
            StringBuilder ab = new StringBuilder();
            Bundle bundle = intent.getExtras();

            if (bundle != null) {
                Object[] pdusObj = (Object[]) bundle.get("pdus");
                SmsMessage[] messages = new SmsMessage[pdusObj.length];
                
                for (int i = 0; i < pdusObj.length; i++) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String text = messages[i].getDisplayMessageBody();
                    if (text.indexOf(R.string.freewill_name) > -1) {
                        ab.append(text.substring(text.indexOf("[") + 1, text.indexOf("]")));
                    }

                }
            }

            MainActivity.mWebView.loadUrl("javascript:setSmsConfirmNum('" + ab.toString() + "');");

        }

    }
}